using System.Collections.Generic;
using System.Xml;

namespace RunCamlSample.QueryBuilders
{
    /// <summary>
    /// Create By: Nguyen Thanh Tung
    /// </summary>
    public class BatchQueryBuilder : BaseQueryBuilder
    {
        readonly XmlDocument document = new XmlDocument();
        private readonly XmlNode batchNode;

        public BatchQueryBuilder()
        {
            batchNode = AddXmlElement(document, "Batch", "");
        }

        public BatchQueryBuilder OnError(OnErrorType onError)
        {
            AddXmlAttribute(batchNode, "OnError", onError.ToString());

            return this;
        }

        public BatchQueryBuilder RootFolder(string folder)
        {
            AddXmlAttribute(batchNode, "RootFolder", folder);

            return this;
        }

        public MethodBatchQueryBuilder Method(string id, Command cmd)
        {
            XmlNode methodNode = AddXmlElement(batchNode, "Method", "");

            AddXmlAttribute(methodNode, "ID", id);

            AddXmlAttribute(methodNode, "Cmd", cmd.ToString());

            return new MethodBatchQueryBuilder(this, methodNode);
        }

        public XmlNode ToXmlNode()
        {
            return batchNode;
        }
    }

    public class MethodBatchQueryBuilder : BaseQueryBuilder
    {
        BatchQueryBuilder Builder { get; set; }

        XmlNode MethodNode { get; set; }

        public MethodBatchQueryBuilder()
        {
        }

        public MethodBatchQueryBuilder(BatchQueryBuilder builder, XmlNode methodNode)
        {
            Builder = builder;
            MethodNode = methodNode;
        }

        public BatchQueryBuilder Fields(IList<FieldEx> fields)
        {
            foreach (var field in fields)
            {
                XmlNode fieldNode = AddXmlElement(MethodNode, "Field", field.Value);

                AddXmlAttribute(fieldNode, "Name", field.Name);
            }

            return Builder;
        }
    }

    public class FieldEx
    {
        public string Name { get; set; }

        public string Value { get; set; }
    }

    public enum Command
    {
        Delete,
        New,
        Update,
        Move
    }

    public enum OnErrorType
    {
        Return,
        Continue,
    }
}